from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
import sys
from mainwindow import Ui_MainWindow
import db as assetHolderDb
from db import Asset
from assetHandler import AssetTabHandler
from brokerHandler import BrokerTabHandler
from positionHandler import PositionTabHandler

DATABASE_NAME = 'base.sqlite'

class AssetHolderApplication(QMainWindow):
	
	def __init__(self, session, parent=None):
		super (AssetHolderApplication, self).__init__(parent)  
		self.session = session
		self.createWidgets()

	def createWidgets(self):
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		# set up values and fill table
		self.db = QSqlDatabase.addDatabase("QSQLITE")
		self.db.setDatabaseName(DATABASE_NAME)
		self.db.open()   
		
		# create signals and all for view :
		# self.summary = HomeSummary(self.db, self.ui) # preparing for summary group handling
		self.assetTabHandler = AssetTabHandler(self.db, self.ui.assetsTableView, self.ui.assetsNewButton, self.ui.assetsDeleteButton, self.ui.assetsHistoryButton, self)
		self.brokerTabHandler = BrokerTabHandler(self.db, self.ui.brokersTableView, self.ui.brokersNewButton, self.ui.brokersDeleteButton, self)
		self.positionTabHandler = PositionTabHandler(self.db, self.ui.positionsTableView, self.ui.positionsNewButton, self.ui.positionsDeleteButton, self)
		

	def handleExit(self):
		"""
		This method is to be used while exiting the application in order to close sessions (SQLAlchemy)
		and Connections opened by QSqlDatabase widget.
		"""
		print("exit in progress")
		self.db.removeDatabase(DATABASE_NAME)
		self.db.removeDatabase('qt_sql_default_connection')
		self.db.close()
		self.session.close()

if __name__ == "__main__":
	app = QApplication(sys.argv)
	myapp = AssetHolderApplication(assetHolderDb.session)
	myapp.show()
	sys.exit(app.exec_())
